package com.shinbada.modules.sys.web;

import com.shinbada.common.ResultCode;
import com.shinbada.common.json.AjaxJson;
import com.shinbada.common.utils.StringUtils;
import com.shinbada.core.persistence.Page;
import com.shinbada.core.web.BaseController;
import com.shinbada.exception.ServiceException;
import com.shinbada.modules.sys.entity.DictType;
import com.shinbada.modules.sys.entity.DictValue;
import com.shinbada.modules.sys.service.DictTypeService;
import com.shinbada.modules.sys.utils.DictUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 字典Controller
 *
 * @author initcap
 * @version 2017-05-16
 */
@RestController
@RequestMapping("/sys/dict")
@Api(tags = "字典管理")
public class DictController extends BaseController {

    @Autowired
    private DictTypeService dictTypeService;

    @ModelAttribute
    public DictType get(@RequestParam(required = false) String id) {
        if (StringUtils.isNotBlank(id)) {
            return dictTypeService.get(id);
        } else {
            return new DictType();
        }
    }

    @RequiresPermissions("user")
    @GetMapping("getDictValue")
    @ApiOperation("根据dictTypeId进行查询")
    public AjaxJson getDictValue(String dictTypeId) {
        Map<String, Object> page = new HashMap<>();
        if (dictTypeId == null || "".equals(dictTypeId)) {
            page.put("list", "[]");
            page.put("count", 0);
        } else {
            List<DictValue> list = dictTypeService.get(dictTypeId).getDictValueList();
            page.put("list", list);
            page.put("count", list.size());
        }
        return AjaxJson.success().put("page", page);
    }

    @RequiresPermissions("user")
    @GetMapping("type/list")
    @ApiOperation("字典类型集合")
    public AjaxJson data(DictType dictType, HttpServletRequest request, HttpServletResponse response) {
        Page<DictType> page = dictTypeService.findPage(new Page<>(request, response), dictType);
        return AjaxJson.success().put("page", page);
    }


    @RequiresPermissions("user")
    @GetMapping("queryById")
    @ApiOperation("根据主键查询字典类型")
    public AjaxJson queryById(DictType dictType) {
        return AjaxJson.success().put("dictType", dictType);
    }

    @RequiresPermissions("user")
    @GetMapping("queryDictValue")
    @ApiOperation("查询字典值")
    public AjaxJson queryDictValue(String dictValueId) {
        DictValue dictValue;
        if (dictValueId == null || "".equals(dictValueId)) {
            dictValue = new DictValue();
        } else {
            dictValue = dictTypeService.getDictValue(dictValueId);
        }
        return AjaxJson.success().put("dictValue", dictValue);
    }


    @RequiresPermissions(value = {"sys:dict:add", "sys:dict:edit"}, logical = Logical.OR)
    @PostMapping("save")
    @ApiOperation("保存字典类型")
    public AjaxJson save(DictType dictType) {
        if (shinProperites.isDemoMode()) {
            return AjaxJson.error("演示模式，不允许操作！");
        }
        /**
         * 后台hibernate-validation插件校验
         */
        String errMsg = beanValidator(dictType);
        if (StringUtils.isNotBlank(errMsg)) {
            return AjaxJson.error(errMsg);
        }
        dictTypeService.save(dictType);
        return AjaxJson.success("保存字典类型'" + dictType.getDescription() + "'成功！");
    }

    @RequiresPermissions("user")
    @PostMapping("saveDictValue")
    @ApiOperation("保存字典值")
    public AjaxJson saveDictValue(String dictValueId, DictValue dictValue) {
        if (shinProperites.isDemoMode()) {
            return AjaxJson.error("演示模式，不允许操作！");
        }
        /**
         * 后台hibernate-validation插件校验
         */
        String errMsg = beanValidator(dictValue);
        if (StringUtils.isNotBlank(errMsg)) {
            return AjaxJson.error(errMsg);
        }
        dictValue.setId(dictValueId);
        dictTypeService.saveDictValue(dictValue);
        return AjaxJson.success("保存键值'" + dictValue.getLabel() + "'成功！");
    }


    @RequiresPermissions("sys:dict:delKey")
    @DeleteMapping("deleteDictValue")
    @ApiOperation("删除字典键值信息")
    public AjaxJson deleteDictValue(String ids) {
        if (shinProperites.isDemoMode()) {
            return AjaxJson.error("演示模式，不允许操作！");
        }
        dictTypeService.batchDeleteDictValue(ids.split(","));
        return AjaxJson.success("删除键值成功！");
    }

    @RequiresPermissions("sys:dict:del")
    @DeleteMapping("delete")
    @ApiOperation("批量删除")
    public AjaxJson delete(String ids) {
        if (shinProperites.isDemoMode()) {
            return AjaxJson.error("演示模式，不允许操作！");
        }
        String[] idArray = ids.split(",");
        boolean containsSystemDict = dictTypeService.containsSystemDict(idArray);
        if (containsSystemDict) {
            throw new ServiceException(ResultCode.DICT_TYPE_SYSTEM_CAN_NOT_DELETE);
        }
        dictTypeService.batchDelete(idArray);
        return AjaxJson.success();
    }


    @GetMapping("listData")
    @ApiOperation("获取数据集合")
    public AjaxJson listData(@RequestParam(required = false) String type) {
        DictType dictType = new DictType();
        dictType.setType(type);
        return AjaxJson.success().put("list", dictTypeService.findList(dictType));
    }

    @GetMapping("getDictMap")
    @ApiOperation("获取字典键值对")
    public AjaxJson getDictMap() {
        return new AjaxJson().put("dictList", DictUtils.getDictMap());
    }

    @GetMapping("getDictList")
    @ApiOperation("根据字典类型获取字典键值对集合")
    public AjaxJson getDictList(@RequestParam(required = true) String type) {
        return AjaxJson.success().put("dictList", dictTypeService.getDictList(type));
    }

    @PostMapping("appendDictValue")
    @ApiOperation("根据字典类型添加键值对数据")
    public AjaxJson appendDictValue(String type, DictValue dictValue) {
        dictTypeService.appendDictValue(type, dictValue);
        return AjaxJson.success();
    }

}
